import useSWR from "swr";
import { fetcher } from "../utils";
import { useNavigate } from "react-router-dom";
import "./GradeList.css";

export default function GradeList(props) {
    const navigate = useNavigate();
    const { data: items, error, mutate } = useSWR("/api/grade/list", fetcher);

    if (error) {
        return <div>数据加载失败</div>;
    }

    if (!items) {
        return <div>数据加载中...</div>;
    }

    const handleDelete = async (stu_sn, cou_sn) => {
        if (!confirm("确定要删除该成绩记录吗？")) return;
        try {
            let response = await fetch("/api/grade/one", {
                method: "DELETE",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ stu_sn, cou_sn }),
            });
            if (!response.ok) {
                alert("删除失败");
                return;
            }
            mutate();
        } catch (e) {
            alert("删除失败");
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <button className="btn" onClick={() => navigate("/grade/edit")}>录入/修改成绩</button>
                <button className="btn" onClick={() => navigate("/grade/report")}>成绩报告</button>
            </div>
            <div className="paper-body">
                <table className="table">
                    <thead>
                        <tr>
                            <th>姓名</th>
                            <th>课程</th>
                            <th>成绩</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {items &&
                            items.map((item, idx) => (
                                <tr key={idx}>
                                    <td>{item.stu_name}</td>
                                    <td>{item.cou_name}</td>
                                    <td>{item.grade}</td>
                                    <td>
                                        <button className="btn" onClick={() => handleDelete(item.stu_sn, item.cou_sn)}>删除</button>
                                    </td>
                                </tr>
                            ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}
